package thread_case;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor {
    // 创建阻塞队列,用来接收任务,这里设置最多容纳任务量为 100
    private BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(100);
    // 创建线程链表,把创建的每个线程都用线程链表组织起来
    private List<Thread> threadList = new ArrayList<>();
    // 构造方法,指定线程池中固定的线程数,并且将线程都创建好
    public MyThreadPoolExecutor(int num) {
        for (int i = 0; i < num; i++) {
            Thread t = new Thread(()->{
                while (true) {
                    // 利用 runnable 来接收阻塞队列中的任务
                    Runnable runnable = null;
                    try {
                        // 获取任务
                        runnable = blockingQueue.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    // 执行任务
                    runnable.run();
                }
            });
            // 启动线程
            t.start();
            // 将线程加入到线程链表中
            threadList.add(t);
        }
    }
    // 方法 sumbit 用来向阻塞队列中添加新的任务
    public void sumbit(Runnable runnable) throws InterruptedException {
        blockingQueue.put(runnable);
    }
}

public class ThreadDemo8 {
    public static void main(String[] args) throws InterruptedException {
        // 创建线程池,指定线程数目为 4
        MyThreadPoolExecutor executor = new MyThreadPoolExecutor(4);
        // 循环 100 次,向线程池中添加 100 个任务
        for (int i = 0; i < 100; i++) {
            int n = i;
            executor.sumbit(new Runnable() {
                @Override
                public void run() {
                    // 任务的内容
                    System.out.println("执行任务:->" + n + ",执行的线程是:->" + Thread.currentThread().getName());
                }
            });
        }
    }
}
